package com.sjtu.bookread;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import androidx.core.content.ContextCompat;
import com.sjtu.bookread.obj.LoginObj;
import com.sjtu.bookread.service.OperateData;
import com.sjtu.bookread.service.RecomService;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.prefs.Preferences;

public class LoginActivity extends AppCompatActivity {

    private EditText user,password;
    private Button login, register;

    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private CheckBox rememberPass;

    public static final String TAG = "LoginActivity";
    private LoginObj loginObj;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        changeStatusIconCollor(true);
        Window window =this.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(ContextCompat.getColor(this,R.color.colorGreyTitle));

        setContentView(R.layout.activity_login1);
        pref = getSharedPreferences("login", Context.MODE_PRIVATE);

        //初始化控件
        init();

        boolean isRemember = pref.getBoolean("remember_password",false);
        if (isRemember) {
            final String user1 = pref.getString("user","");
            final String password1 = pref.getString("password","");
            user.setText(user1);
            password.setText(password1);
            rememberPass.setChecked(true);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    Looper.prepare();
                    loginObj = RecomService.getRecomService().getLogin(user1, password1);
                    if (loginObj != null && loginObj.getType().equals("0")) {
                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("user_name", user1);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        LoginActivity.this.finish();
                    } else
                    {
                        Toast.makeText(LoginActivity.this,"登录失败",Toast.LENGTH_SHORT).show();
                    }
                    Looper.loop();
                }
            }).start();
        }

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String inputUser = user.getText().toString();
                final String inputPassword = password.getText().toString();
                final boolean inputRemember = rememberPass.isChecked();

                if (TextUtils.isEmpty(inputUser)) {
                    Toast.makeText(LoginActivity.this,"请输入用户名",Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(inputPassword)) {
                    Toast.makeText(LoginActivity.this,"请输入密码",Toast.LENGTH_SHORT).show();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Looper.prepare();
                            loginObj = RecomService.getRecomService().getLogin(inputUser,inputPassword);
                            if (loginObj != null && loginObj.getType().equals("0")) {
                                Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                                // Load into shared preference
                                SharedPreferences.Editor editor = pref.edit();
                                editor.putBoolean("remember_password", inputRemember);
                                editor.putString("password", inputPassword);
                                editor.putString("user", inputUser);
                                editor.commit();

                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putString("user_name", inputUser);
                                intent.putExtras(bundle);
                                startActivity(intent);
                                LoginActivity.this.finish();
                            } else
                            {
                                Toast.makeText(LoginActivity.this,"登录失败",Toast.LENGTH_SHORT).show();
                            }
                            Looper.loop();
                        }
                    }).start();
                }
            }
        });

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
    }

    public void changeStatusIconCollor(boolean setDark) {
        View decorView = getWindow().getDecorView();
        if(decorView != null){
            int vis = decorView.getSystemUiVisibility();
            if(setDark){
                vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            } else{
                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            }
            decorView.setSystemUiVisibility(vis);
        }
    }

    private void init(){
        login = findViewById(R.id.login);
        register = findViewById(R.id.register);
        user = findViewById(R.id.user);
        password = findViewById(R.id.password);
        rememberPass = findViewById(R.id.remember);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(user.getWindowToken(), 0);
            imm.hideSoftInputFromWindow(password.getWindowToken(), 0);
        }
        return super.dispatchTouchEvent(ev);
    }
}
